package com.thread.lock.money.second;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @description:
 * @author: 刘建楼
 * @create: 2021-04-20
 **/
public class Account2 {

    private final ReentrantLock lock = new ReentrantLock();

    private String accountNo;
    private double balance;

    // synchronized 和 lock用一个即可
    public synchronized void draw(double drawAmount) {
        lock.lock();
        try {
            if (balance >= drawAmount) {
                // 吐出钞票
                System.out.println(Thread.currentThread().getName() + "取钱成功！吐出钞票：" + drawAmount);
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 修改余额
                balance -= drawAmount;
                System.out.println("余额为:" + balance);
            } else {
                System.out.println("取钱失败！ 余额不足");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    // 下面两个方法根据accountNo来重写hashCOde()和equals()方法
    public int hashCode() {
        return accountNo.hashCode();
    }

    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        ;
        if (obj != null && obj.getClass() == Account2.class) {
            Account2 account2 = (Account2) obj;
            return account2.getAccountNo().equals(accountNo);
        }
        return false;
    }


    public Account2() {
    }

    public Account2(String accountNo, double balance) {
        this.accountNo = accountNo;
        this.balance = balance;
    }

    public String getAccountNo() {
        return accountNo;
    }

    public void setAccountNo(String accountNo) {
        this.accountNo = accountNo;
    }

    public double getBalance() {
        return balance;
    }

}
